package TCPSocket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 王艺锡
 * @version 1.0
 */
public class SocketTCP03Server {
    public static void main(String[] args) throws IOException {
//1.在本机的9999端口监听，等待连接
        //要求本机没有其他服务在监听9999端口
        //注:ServerSocket可以通过accept()返回多个Socket对象[多个客户端连接服务器的并发]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端，在9999端口监听，等待连接...");
        //2.当没有客户端连接9999端口的时候，程序会阻塞，等待连接
        //  如果有客服端连接，则会被接收，程序继续
        Socket socket = serverSocket.accept();
        //3.通过socket.getInputStream() 读取客户端写入到数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = " ";
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }

        //4.回复hello,client,使用字符流
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        //3.通过输出流，写入数据到数据通道
        bw.write("hello,client");
        bw.newLine();
        bw.flush();
        socket.shutdownOutput();


        //5.关闭对应的流和socket
        br.close();
        bw.close();
        socket.close();
        serverSocket.close();
    }
}
